import click
import os
import json
import subprocess
import time
from mail_send import send_email_2_revcer


@click.command()
@click.option(
    "--smtp-pwd",
    "-s",
    envvar="smtp_pwd",
    required=False,
    default=None,
    type=click.STRING,
    help="smtp_pwd",
    metavar="smtp_pwd",
)
def sdk_ci_test(smtp_pwd=None):
    execute_command("pip install pytest-xdist")
    execute_command("pip install pyyaml")
    execute_command("pip install PyEmail")
    execute_command("rm -rf /rt-thread/hello_test")
    execute_command("chmod 777 prj_gen")
    # get sdk
    with open('/rt-thread/sdk-index/tools/sdk_url.json', "r") as f:
        sdk_url = json.loads(f.read())[0]
    execute_command("wget -c {0}".format(sdk_url))
    zip_name = sdk_url.split("/")[-1]
    execute_command("unzip {0}".format(zip_name))
    execute_command("rm -rf {0}".format(zip_name))
    # gen project json file
    execute_command("python csp_parameter_json_file_generator.py")
    # gen mcu_config dir
    execute_command("python test_list.py")
    # pytest
    os.system("python project_test.py")
    # send_email_2_revcer("liukang@rt-thread.com", "report.html", smtp_pwd)


def execute_command(cmd_string, cwd=None, shell=True):
    """Execute the system command at the specified address."""

    sub = subprocess.Popen(cmd_string, cwd=cwd, stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE, shell=shell, bufsize=4096)

    stdout_str = ''
    while sub.poll() is None:
        stdout_str += str(sub.stdout.read())
        time.sleep(0.1)

    return stdout_str


if __name__ == "__main__":
    sdk_ci_test()
